﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Wwtfly.BBS.BackBLL.Users;
using Wwtfly.BBS.Enums.Common;
using Wwtfly.BBS.BackModels.Models.Users;
using System.Web.Mvc;
using System.Web;
using System.IO;
using Wwtfly.LoggerUtility;
using Wwtfly.BBS.BackModels.Models.Users.Right;

namespace Wwtfly.BBS.BackControllers.Common
{
    /// <summary>
    /// 生成菜单 
    /// </summary>
    public class CreateMenu
    {

        const string FUNC = "FUNC";
        const string MENU = "MENU";

        const string item = "{0} = {1}.Item(\"{2}\");";
        const string itemIcon = "{0} = {1}.Item(\"{2}\", window.ImageResources +\"{3}\");";
        const string link = "{0}.Link(\"{1}\", \"{2}\", {3});";
        const string linkIcon = "{0}.Link(\"{1}\", \"{2}\", {3}, window.ImageResources +\"{4}\");";




        /// <summary>
        /// 生成菜单..
        /// </summary>
        /// <param name="model"></param>
        /// <param name="menuType"></param>
        public static bool CreateUAMenuInfo(UsersModel model, ModuleTypeEnum menuType, UrlHelper url,
            HttpServerUtilityBase server)
        {
            try
            {

                //写入
                string path = server.MapPath("~/Temp/BackMenu/");
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                path += string.Format("/Menu{0}{1}.js", (int)menuType, model.Id);

                //生成菜单 
                IList<UAMenuInfoModel> menuInfoAllList =
                    UsersBLL.GetUAMenuInfoList((model.IsSuperMan ? -1 : model.Id),
                    ModuleTypeEnum.BACKBBS);
                if (menuInfoAllList == null || menuInfoAllList.Count <= 0)
                {
                    File.Delete(path);
                    return false;
                }
                StringBuilder sb = new StringBuilder();
                sb.Append("function CreateMenuItems(m) {");
                sb.Append("var item1,item2,item3,item4,item5,item6;");

                List<UAMenuInfoModel> myMenuList = menuInfoAllList
            .Where(m => m.ParentMenuID == "0")
            .OrderBy(m => m.OrderID)
            .ToList();
                CreateMenuItems(menuInfoAllList, myMenuList, sb, url, null,0);

                sb.Append("}");
                
                using (StreamWriter sw = new StreamWriter(path, false))
                {
                    sw.WriteLine(sb.ToString());
                }
                return true;
            }
            catch (Exception ex)
            {
                LoggerManage.Error(new LogMessageParams()
                {
                    ModuleID = "UsersBLL",
                    FuncCode = "CreateUAMenuInfo",
                    Level = AppErrorLevel.EROR,
                    ErrCode = "0x0",
                    Excep = ex,
                    logMessage = "生成菜单...出错",
                    ProgramName = "Wwtilfy.BBS"
                });
                return false;
            }

        }


        #region Private methods

        // 删除菜单
        //private void DeleteMenuItems(int userGroupId, LanguageEnum language)
        //{
        //    string path = Server.MapPath(Url.Content(
        //        string.Format("~/WebResources/Generate/Menu{0}{1}.js", userGroupId, (int)language)));
        //    if (System.IO.File.Exists(path))
        //    {
        //        System.IO.File.Delete(path);
        //    }
        //}

        /// <summary>
        /// // 生成菜单
        /// </summary>
        /// <param name="menuInfoList"></param>
        /// <param name="sb"></param>
        /// <param name="model"></param>
        /// <param name="menuType"></param>
        /// <param name="url"></param>
        /// <param name="server"></param>
        /// <param name="parentMenuID">父节点</param>
        /// <param name="count">调用次数</param>
        /// <returns></returns>
        private static void CreateMenuItems(IList<UAMenuInfoModel> menuInfoAllList,
            IList<UAMenuInfoModel> menuInfoList,
            StringBuilder sb, UrlHelper url, string parentMenuID,int count)
        {
            count++;
            foreach (var myMenu in menuInfoList)
            {
                if (string.IsNullOrEmpty(myMenu.LinkURL))
                {
                    if (string.IsNullOrEmpty(myMenu.ImageURL))
                    {
                        sb.AppendFormat(item, "item" + count, count == 1 ? "m" : "item" + (count-1), myMenu.MenuName);
                    }
                    else
                    {
                        sb.AppendFormat(itemIcon, "item" + count, count == 1 ? "m" : "item" + (count - 1), myMenu.MenuName, url.Content(myMenu.ImageURL));

                    }
                }
                else
                {
                    //有链接的...
                    if (string.IsNullOrEmpty(myMenu.ImageURL))
                    {
                        sb.AppendFormat(link,
                            "item" + (count-1),
                             myMenu.MenuName,
                           url.Content(myMenu.LinkURL),
                            false.ToString().ToLower());
                    }
                    else
                    {
                        sb.AppendFormat(linkIcon,
                            "item" + (count - 1),
                             myMenu.MenuName,
                           url.Content(myMenu.LinkURL),
                            myMenu.ImageURL);
                    }
                }
               
                List<UAMenuInfoModel> nextMentList = menuInfoAllList
           .Where(m => m.ParentMenuID == myMenu.MenuID)
           .OrderBy(m => m.OrderID)
           .ToList();
                if (nextMentList != null && nextMentList.Count > 0)
                {
                    CreateMenuItems(menuInfoAllList, nextMentList, sb, url, myMenu.MenuID,count);
                }
            }

        }

        #endregion
    }
}